package manager.modulo.sistema.fonte;

import java.sql.SQLException;
import java.util.LinkedList;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import manager.auxiliares.*;
import manager.helpers.validation.PasswordFieldValidator;
import manager.helpers.validation.TextFieldValidator;
import manager.helpers.validation.ValidationFunctions;
import manager.modulo.sistema.dao.ModuleDao;
import manager.modulo.sistema.dao.UsuarioDao;
import manager.modulo.sistema.enumerator.EnumSituacaoUsuario;
import manager.principal.fonte.JanelaLogin;

/**
 *
 * @author Thiago
 */
public class JanelaUsuario extends javax.swing.JFrame {

    int idUser = 0;

    /**
     * Creates new form JanelaUsuario
     */
    public JanelaUsuario(int newIdUser) {
        try {
            // Define layout de acordo com o SO que estiver rodando
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            this.setIconImage(JanelaLogin.icon);
            initComponents();
            idUser = newIdUser;
            configureWindow();
            this.setLocationRelativeTo(null);
            this.setVisible(true);

        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, "Usuários");
        }
    }

    private void checkRequiredFields() {
        ((TextFieldValidator) jTextField1).validarCampo();
        ((PasswordFieldValidator) jPasswordField1).validarCampo();
        ((TextFieldValidator) jTextField4).validarCampo();
    }

    private LinkedList<String> validateFields() {
        LinkedList<String> fieldList = new LinkedList<String>();
        if (!((TextFieldValidator) jTextField1).validarCampo()) {
            fieldList.add(((TextFieldValidator) jTextField1).getjLabel().getText());
        }
        if (!((PasswordFieldValidator) jPasswordField1).validarCampo()) {
            fieldList.add(((PasswordFieldValidator) jPasswordField1).getjLabel().getText());
        }
         if (!((TextFieldValidator) jTextField4).validarCampo()) {
            fieldList.add(((TextFieldValidator) jTextField4).getjLabel().getText());
        }
        return fieldList;
    }

    private void addUser() {
        try {
            if (UsuarioDao.getIdUsuarioPorEmail(jTextField1.getText()) == 0) {
                try {
                    JanelaLogin.connection.setAutoCommit(false);

                    UsuarioDao userDao = new UsuarioDao();
                    userDao.setEmail(jTextField1.getText());
                    userDao.setSenha(Encryption.encrypt(jPasswordField1.getText()));
                    userDao.setSituacao(EnumSituacaoUsuario.ConvertStringEnum(jComboBox1.getSelectedItem().toString()));
                    userDao.setNome(jTextField4.getText());
                    userDao.inserir();

                    ModuleDao.insertModulePermission(getAllowedModules(), userDao.getId());

                    JanelaLogin.connection.commit();

                    JOptionPane.showMessageDialog(null, "Usuário cadastrado com sucesso.", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);
                    this.dispose();
                } catch (Exception e) {
                    JanelaLogin.connection.rollback();
                    MensagemExcessao.mostrarMensagem(e, this.getTitle());
                } finally {
                    JanelaLogin.connection.setAutoCommit(true);
                }
            } else {
                JOptionPane.showMessageDialog(null, "Este email já esta cadastrado.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception ex) {
            MensagemExcessao.mostrarMensagem(ex, this.getTitle());
        }
    }

    private void setEntityInformations() {
        jButton1.setText("Editar");
        jButton1.setIcon(new Icons().getEdit());

        UsuarioDao userDao = new UsuarioDao();
        userDao.buscar(idUser);
        jTextField1.setText(userDao.getEmail());
        jTextField4.setText(userDao.getNome());
        jComboBox1.setSelectedItem(EnumSituacaoUsuario.ConvertEnumString(userDao.getSituacao()));
    }

    private void editUser() {
        try {
            UsuarioDao userDao = new UsuarioDao();
            userDao.buscar(idUser);
            if (UsuarioDao.getIdUsuarioPorEmail(jTextField1.getText()) == 0 || userDao.getEmail().equals(jTextField1.getText())) {
                try {
                    JanelaLogin.connection.setAutoCommit(false);

                    userDao.setEmail(jTextField1.getText());
                    userDao.setSenha(Encryption.encrypt(jPasswordField1.getText()));
                    userDao.setSituacao(EnumSituacaoUsuario.ConvertStringEnum(jComboBox1.getSelectedItem().toString()));
                    userDao.setNome(jTextField4.getText());
                    userDao.atualizar();

                    ModuleDao.deletePermissions(idUser);

                    ModuleDao.insertModulePermission(getAllowedModules(), idUser);

                    JanelaLogin.connection.commit();

                    JOptionPane.showMessageDialog(null, "Usuário editado com sucesso.", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);
                    this.dispose();
                } catch (Exception e) {
                    JanelaLogin.connection.rollback();
                    MensagemExcessao.mostrarMensagem(e, this.getTitle());
                } finally {
                    JanelaLogin.connection.setAutoCommit(true);
                }
            } else {
                JOptionPane.showMessageDialog(null, "Este email já esta cadastrado.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception ex) {
            MensagemExcessao.mostrarMensagem(ex, this.getTitle());
        }
    }

    /**
     * Inicializando as configurações da tela
     *
     * @throws SQLException
     */
    private void configureWindow() throws SQLException {
        ((PasswordFieldValidator) jPasswordField1).setConfirmPassword(jPasswordField2);
        ((PasswordFieldValidator) jPasswordField2).setConfirmPassword(jPasswordField1);
        if (idUser != 0) { // Edição de usuário
            setEntityInformations();
        }
        configureModulesPermissions();

        this.checkRequiredFields();
    }

    private void configureModulesPermissions() throws SQLException {
        LinkedList<String> userModules = (this.idUser != 0) ? ModuleDao.modulesByIdUser(this.idUser) : new LinkedList<String>();
        DefaultListModel allowedModelList = new DefaultListModel();
        jList1.setModel(allowedModelList);
        LinkedList<String> systemModules = ModuleDao.systemModules();
        DefaultListModel disallowedModelList = new DefaultListModel();
        jList2.setModel(disallowedModelList);

        for (int i = 0; i < systemModules.size(); i++) {
            String module = systemModules.get(i);
            if (userModules.contains(module)) {
                allowedModelList.addElement(module);
            } else {
                disallowedModelList.addElement(module);
            }
        }
    }

    /**
     * Transfere elementos da lista de modulos não permitidos, e os passa para
     * lista de permitidos.
     *
     * @param all Este parâmetro indica se todos os elementos serão transferidos
     */
    private void passDisallowedToAllowed(boolean all) {

        DefaultListModel allowedModel = (DefaultListModel) jList1.getModel();
        DefaultListModel disallowedModel = (DefaultListModel) jList2.getModel();
        for (int i = 0; i < disallowedModel.getSize(); i++) {
            if (jList2.isSelectedIndex(i) || all) {
                allowedModel.addElement(disallowedModel.getElementAt(i));
                disallowedModel.remove(i);
                i--;
            }
        }
    }

    /**
     * Remove os elementos selecionados da lista de modulos permitidos, e os
     * passa para lista de não permitidos.
     *
     * @param all
     */
    private void passAllowedToDisallowed(boolean all) {
        DefaultListModel disallowedModel = (DefaultListModel) jList2.getModel();
        DefaultListModel allowedModel = (DefaultListModel) jList1.getModel();
        for (int i = 0; i < allowedModel.getSize(); i++) {
            if (jList1.isSelectedIndex(i) || all) {
                disallowedModel.addElement(allowedModel.getElementAt(i));
                allowedModel.remove(i);
                i--;
            }
        }
    }

    private LinkedList<String> getAllowedModules() {
        DefaultListModel allowedModel = (DefaultListModel) jList1.getModel();
        LinkedList<String> allowedModules = new LinkedList<String>();
        for (int i = 0; i < allowedModel.getSize(); i++) {
            allowedModules.add((String) allowedModel.getElementAt(i));
        }
        return allowedModules;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel3 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jTextField1 = new manager.helpers.validation.TextFieldValidator(60,-1,true,false,"email",jLabel1);
        jPasswordField1 = new PasswordFieldValidator(20, 4, true, false, "text", jLabel2);
        jPasswordField2 = new PasswordFieldValidator(20, 4, true, false, "text", jLabel3);
        jPanel2 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        jList2 = new javax.swing.JList();
        jButton1 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel7 = new javax.swing.JLabel();
        jTextField4 = new TextFieldValidator(60, -1, true, true, "text", jLabel7);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Usuários");
        setBackground(Configurations.getBackGroundColor());
        setMinimumSize(new java.awt.Dimension(700, 360));
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        jPanel3.setBackground(Configurations.getBackGroundColor());
        jPanel3.setPreferredSize(new java.awt.Dimension(700, 320));
        jPanel3.setLayout(null);

        jPanel1.setBackground(Configurations.getBackGroundColor());
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel1.setLayout(null);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setText("E-mail");
        jPanel1.add(jLabel1);
        jLabel1.setBounds(20, 20, 220, 14);

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel2.setText("Senha");
        jPanel1.add(jLabel2);
        jLabel2.setBounds(305, 20, 90, 14);

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel3.setText("Confirmação da Senha");
        jPanel1.add(jLabel3);
        jLabel3.setBounds(440, 20, 130, 14);

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel4.setText("Situação");
        jPanel1.add(jLabel4);
        jLabel4.setBounds(575, 20, 90, 14);
        jPanel1.add(jTextField1);
        jTextField1.setBounds(20, 40, 280, 20);
        jPanel1.add(jPasswordField1);
        jPasswordField1.setBounds(305, 40, 130, 20);
        jPanel1.add(jPasswordField2);
        jPasswordField2.setBounds(440, 40, 130, 20);

        jPanel2.setBackground(Configurations.getBackGroundColor());
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("MÓDULOS DO SISTEMA"));
        jPanel2.setLayout(null);

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel5.setText("Permitidos");
        jPanel2.add(jLabel5);
        jLabel5.setBounds(15, 20, 260, 14);

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel6.setText("Não Permitidos");
        jPanel2.add(jLabel6);
        jLabel6.setBounds(360, 20, 260, 14);

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/reward.png"))); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton2);
        jButton2.setBounds(300, 40, 30, 30);

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/forward.png"))); // NOI18N
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton3);
        jButton3.setBounds(300, 80, 30, 30);

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/fast_reward.png"))); // NOI18N
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton4);
        jButton4.setBounds(300, 130, 30, 30);

        jButton5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/fast_forward.png"))); // NOI18N
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton5);
        jButton5.setBounds(300, 170, 30, 30);

        jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jList1ValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jList1);

        jPanel2.add(jScrollPane1);
        jScrollPane1.setBounds(15, 40, 260, 160);

        jList2.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jList2ValueChanged(evt);
            }
        });
        jScrollPane2.setViewportView(jList2);

        jPanel2.add(jScrollPane2);
        jScrollPane2.setBounds(360, 40, 260, 160);

        jPanel1.add(jPanel2);
        jPanel2.setBounds(30, 120, 635, 210);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/add.png"))); // NOI18N
        jButton1.setText("Cadastrar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton1);
        jButton1.setBounds(20, 340, 100, 23);

        jButton6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/cancel.png"))); // NOI18N
        jButton6.setText("Cancelar");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton6);
        jButton6.setBounds(130, 340, 100, 23);

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "ATIVADO", "DESATIVADO" }));
        jPanel1.add(jComboBox1);
        jComboBox1.setBounds(575, 40, 110, 20);

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel7.setText("Nome");
        jPanel1.add(jLabel7);
        jLabel7.setBounds(20, 70, 70, 14);

        jTextField4.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jPanel1.add(jTextField4);
        jTextField4.setBounds(20, 90, 550, 20);

        jPanel3.add(jPanel1);
        jPanel1.setBounds(0, 0, 700, 380);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 380, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        WindowsFunctions.resizePanel(jPanel3, jPanel1);
    }//GEN-LAST:event_formComponentResized

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        LinkedList<String> fieldValidadeList = validateFields();
        if (fieldValidadeList.size() == 0) {
            if (idUser == 0) {
                addUser();
            } else {
                editUser();
            }
        } else {
            JOptionPane.showMessageDialog(null, ValidationFunctions.getValidationMessage(fieldValidadeList), this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton6ActionPerformed

    private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jList1ValueChanged
        int selectedIndex = jList1.getSelectedIndex();
        if (selectedIndex != -1) {
            jList2.clearSelection();
        }
    }//GEN-LAST:event_jList1ValueChanged

    private void jList2ValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jList2ValueChanged
        int selectedIndex = jList2.getSelectedIndex();
        if (selectedIndex != -1) {
            jList1.clearSelection();
        }
    }//GEN-LAST:event_jList2ValueChanged

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        passDisallowedToAllowed(false);
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        passAllowedToDisallowed(false);
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        passDisallowedToAllowed(true);
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        passAllowedToDisallowed(true);
    }//GEN-LAST:event_jButton5ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JList jList1;
    private javax.swing.JList jList2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPasswordField jPasswordField1;
    private javax.swing.JPasswordField jPasswordField2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField4;
    // End of variables declaration//GEN-END:variables
}
